package edu.nju.cineplex.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.nju.cineplex.dao.DaoHelper;
import edu.nju.cineplex.dao.SeatDao;
import edu.nju.cineplex.model.Seat;

public class SeatDaoImpl implements SeatDao {
	private static SeatDaoImpl seatDao = new SeatDaoImpl();
	private static DaoHelper daoHelper = DaoHelperImpl.getBaseDaoInstance();
	
	private SeatDaoImpl(){
		
	}
	
	public static SeatDao getInstance(){
		return seatDao;
	}
	
	@Override
	public Seat findBySeatNo(String seatNo) {
		// TODO Auto-generated method stub
		Connection con = daoHelper.getConnection();
		PreparedStatement stmt = null;
		ResultSet result = null;
		try {
			stmt = con.prepareStatement("select * from seat where seatNo = ?");
			stmt.setString(1, seatNo);
			result = stmt.executeQuery();
			if (result.next()) {
				Seat seat = new Seat();
				seat.setId(result.getLong(1));
				seat.setSeatNo(seatNo);
				return seat;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			daoHelper.closeConnection(con);
			daoHelper.closePreparedStatement(stmt);
			daoHelper.closeResultSet(result);
		}
		return null;
	}

	@Override
	public List<Seat> findAllSeat() {
		// TODO Auto-generated method stub
		Connection con = daoHelper.getConnection();
		PreparedStatement stmt = null;
		ResultSet result = null;
		List<Seat> allSeat = new ArrayList<Seat>();
		try {
			stmt = con.prepareStatement("select * from seat");
			result = stmt.executeQuery();
			while (result.next()) {
				Seat seat = new Seat();
				seat.setId(result.getLong(1));
				seat.setSeatNo(result.getString(2));
				allSeat.add(seat);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			daoHelper.closeConnection(con);
			daoHelper.closePreparedStatement(stmt);
			daoHelper.closeResultSet(result);
		}
		return allSeat;
	}

}
